import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
} from '@nestjs/websockets'
import { SocketService } from './socket.service'
import { CreateSocketDto } from './dto/create-socket.dto'
import { UpdateSocketDto } from './dto/update-socket.dto'
import { Logger } from '@nestjs/common'
import { ConnectedSocket, WsResponse } from '@nestjs/websockets'
import { Socket } from 'socket.io'
/** @WebSocketGateway装饰器可传入一些配置选项，如下面的示例：
 *   @WebSocketGateway(80, {
 *     namespace: 'events',
 *     transports: ['websocket']
 *     cors: {
 *        origin: '*'
 *     },
 *     ...
 *   })
 **/

let clientList = []

@WebSocketGateway({ cors: true })
export class SocketGateway {
  constructor(private readonly socketService: SocketService) {}

  @SubscribeMessage('connection')
  handleConnection(socket) {
    console.log(socket.id, socket.handshake.query.userId)
    clientList.push({
      id: socket.id,
      userId: socket.handshake.query.userId,
    })

    socket.emit('connection', clientList)
    socket.on('disconnect', () => {
      console.log("断开连接");
      // console.log(socket.id)
      
      clientList = clientList.filter((item) => item.id !== socket.id)
      console.log(clientList);
      
    })
  }


  //简单确认信息示例
  @SubscribeMessage('socketTest')
  socketTest(@MessageBody() data: any) {
    Logger.log('客户端发送的数据：' + JSON.stringify(data))
    return {
      msg1: '测试1',
      msg2: '测试2',
    }
  }
  //转发示例
  @SubscribeMessage('socketTest_Event')
  socketTest_Event(@MessageBody() data: any) {
    Logger.log('客户端发送的数据：' + JSON.stringify(data))
    return {
      event: 'socketTest2',
      data,
    }
  }

  // 广播示例
  @SubscribeMessage('socketTest_Broadcast')
  socketTest_Broadcast(
    @MessageBody() data: any,
    @ConnectedSocket() client: Socket
  ) {
    Logger.log('客户端发送的数据：' + JSON.stringify(data))
    client.broadcast.emit('socketTest3', data)
  }

  @SubscribeMessage('sendMessage')
  sendMessage(client: Socket, data: unknown) {
    Logger.log('客户端发送的数据：' + JSON.stringify(data))
    // client.broadcast.emit('events', data);
    const event = 'sendMessage'
    console.log(clientList)

    // return { event, data }
    client.emit('getMessage', data) //返回给客户端
    // client.broadcast.emit('getMessage', data);//广播给其他客户端
    let data1: any = data
    if (clientList.length > 0) {
      for (let i = 0; i < clientList.length; i++) {
        const element = clientList[i]
        if (element.userId == data1.toUserId) {
          console.log()
          client.to(element.id).emit('getMessage', data)
          return
        }
      }
    }
  }
}
